﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using Assets;
using Assets.game;

public class Root : MonoBehaviour {

    SocketClient client;
    public GComponent view;
    public GComponent com;
    public Window win;
    public Controller c1;
    public int room;
    public AudioSource bgmSource;
    public AudioSource soundSource;

    public static Root instance;

  
	// Use this for initialization
	void Start () {

        initViews();

        //创建ClientWindow（客户端连接窗口）
        com = UIPackage.CreateObject("Package1", "ClientWindow").asCom;
        com.GetChild("n10").onClick.Add(BtnCancelClick);
        com.GetChild("n9").onClick.Add(() =>
        {
            com.GetChild("n9").enabled = false;
            com.GetChild("error").asTextField.text = "";
            string host = com.GetChild("host").asTextInput.text;
            int port = 0;
            if (!Int32.TryParse(com.GetChild("port").asTextInput.text, out port))
            {
                com.GetChild("n9").enabled = true;
                com.GetChild("error").asTextField.text = "端口号输入错误";
                return;
            }
            client = new SocketClient(host,port);
            client.StartException = new Action<Exception>((Exception e) =>
            {
                Debug.LogException(e);
                com.GetChild("error").asTextField.text = "连接服务异常：" + e.Message;
                com.GetChild("n9").enabled = true;
            });
            client.HandleException = new Action<Exception>((Exception e) =>
            {
                Debug.LogException(e);
            });
            client.HandleClientStarted = new Action<SocketClient>(theClient =>
            {
                Debug.Log("socket connected to " + theClient._socket.RemoteEndPoint.ToString());
            });
            client.HandleRecMsg = ClientMessage.message;
            client.StartClient();
        });
        //弹出ClientWindow
        win = new Window();
        win.contentPane = com;
        win.Center();
        win.modal = true;
        win.Show();
	}
	
	// Update is called once per frame
	void Update () {
	}

    void OnDestroy()
    {
        try
        {
            if (client != null && client._socket.Connected)
            {
                client._socket.Close();
            }
        }
        catch
        {

        }
    }

    void BtnCancelClick()
    {
    #if UNITY_EDITOR
        UnityEditor.EditorApplication.isPlaying = false;
    #else
        Application.Quit();
    #endif
    }

    private void initViews()
    {
        //初始化赋值一些组件
        instance = this;

        Loom.Initialize();
        UIPanel panel = gameObject.GetComponent<UIPanel>();
        view = panel.ui;


        t1 = view.GetTransition("p1");
        t1.timeScale = 4.5f;
        t2 = view.GetTransition("p2");
        t2.timeScale = 4.5f;
        t3 = view.GetTransition("p3");
        t3.timeScale = 4.5f;

        selfList = view.GetChild("self").asList;
        selfList.onClickItem.Add(context => {
            GComponent card = (GComponent)context.data;
            if (card.data == null)
            {
                card.data = 1;
                card.y = card.y - 20;
            }
            else
            {
                card.data = null;
                card.y = card.y + 20;
            }
        });

        c1 = view.GetController("c1");

        psLeft = view.GetChild("ps_left").asTextField;
        psRight = view.GetChild("ps_right").asTextField;

        bgmSource = gameObject.GetComponents<AudioSource>()[0];
        soundSource = gameObject.GetComponents<AudioSource>()[1];
    }

    //进入“休闲模式”界面
    public void startGame()
    {
        win.Hide();
        bgmSource.clip = Resources.Load<AudioClip>("Audio/welcome");
        bgmSource.Play();
        Invoke("doStartGame", 3);
    }

    //进入房间界面
    public void doStartGame()
    {
        
        c1.selectedPage = "dengdai";
        client.Send(Message.CLIENT_START_ROOM().ToJson());
    }

    //开始一局游戏
    public void startRoom(int[] paras,List<Card> cards)
    {
        //paras: room.index, i,list.Count, qdz, ai1Dizhu,ai2Dizhu
        room = paras[0];
       
        c1.selectedPage = "fapai";

       
        Debug.Log("开始发牌...");
        
        soundSource.PlayOneShot(Resources.Load<AudioClip>("Audio/Special_Dispatch"));

        fapai(cards);
    }

    
    private Transition t1;
    private Transition t2;
    private Transition t3;
    private GList selfList;
    private GTextField psLeft;
    private GTextField psRight;
    //发牌函数
    public void fapai( List<Card> fapaiCards,int n = 0)
    {
        
        if (n == 17)
        {
            view.GetChild("fp").visible = false;
            Debug.Log("发牌完毕!");
            return;
        }
       
        t1.Play(() =>
        {
            //发玩家的牌
            selfList.AddChild(renderCard(fapaiCards[n]));
            t2.Play(() => 
            {
                //发左边玩家的牌
                GImage bpkLeft = UIPackage.CreateObject("Package1", "bpk").asImage;
                bpkLeft.SetXY(175 - 4 * n, 280 + 5 * n);
                bpkLeft.name = "bpk_left" + n;
                bpkLeft.AddRelation(GRoot.inst, RelationType.Top_Top);
                bpkLeft.AddRelation(GRoot.inst, RelationType.Left_Left);
                view.AddChildAt(bpkLeft, view.GetChildIndex(psLeft));
                psLeft.text = Convert.ToString(n + 1);
                t3.Play(() => { 
                    //发右边玩家的牌
                    GImage bpkRight = UIPackage.CreateObject("Package1", "bpk").asImage;
                    bpkRight.SetXY(780 + 4 * n, 280 + 5 * n);
                    bpkRight.scale = new Vector2(-1, 1);   //左右翻转
                    bpkRight.name = "bpk_right" + n;
                    bpkRight.AddRelation(GRoot.inst, RelationType.Top_Top);
                    bpkRight.AddRelation(GRoot.inst, RelationType.Right_Right);
                    view.AddChildAt(bpkRight, view.GetChildIndex(psRight));
                    
                    psRight.text = Convert.ToString(n + 1);
                    //递归继续发牌
                    fapai(fapaiCards,n+1);
                });
            });
        });
       
    }

    //渲染card对象为GComponent
    public GComponent renderCard(Card card)
    {
        if (card.display == "xiaowang")
        {
            return UIPackage.CreateObject("Package1", "BlackJoker").asCom;
        }
        else if (card.display == "dawang")
        {
            return UIPackage.CreateObject("Package1", "RedJoker").asCom;
        }
        GComponent com = UIPackage.CreateObject("Package1", "Card").asCom;
        com.GetChild("suit").asTextField.text = card.suit;
        GTextField text = com.GetChild("number").asTextField;
        TextFormat tf = text.textFormat;
        if (card.suit == "1" || card.suit == "3")
        {
            //红色
            tf.font = "ui://Package1/red";
        }
        else
        {
            //黑色
            tf.font = "ui://Package1/black";
        }
        text.textFormat = tf;
        text.text = card.display;
        return com;
    }

   

}
